import socket
import ssl
import time

class server_ssl:
    def build_listen(self):
        # 生成SSL上下文
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        # 加载服务器所用证书和私钥
        context.load_cert_chain('server.crt', 'server.key')
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
        sock.bind(('127.0.0.1', 9443))
        sock.listen(5)
        ssock = context.wrap_socket(sock, server_side=True)
        # 监听端口
        # with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
        #     sock.bind(('127.0.0.1', 9443))
            # sock.listen(5)
            # 将socket打包成SSL socket，其主要工作是完成密钥协商
            # with context.wrap_socket(sock, server_side=True) as ssock:
        while True:
            # 接收客户端连接
            client_socket, addr = ssock.accept()
            # 接收客户端信息
            # msg = client_socket.recv(1024).decode("utf-8")
            # print(f"receive msg from client {addr}：{msg}")
            # 向客户端发送信息
            # msg = f"yes , you have client_socketect with server.\r\n".encode("utf-8")
            # client_socket.send(msg)
            while True:
                data = client_socket.recv(1024)
                print('客户端发送内容：', data.decode('utf-8'))
                reply = input('回复：').strip()
                msg = time.strftime('%Y-%m-%d %X')  # 获取结构化时间戳
                msg1 = '[%s]:%s' % (msg, reply)
                client_socket.send(msg1.encode('utf-8'))
            client_socket.close()

if __name__ == "__main__":
    server = server_ssl()
    server.build_listen()